package edu.gzy.rpsm_property.controller;

import edu.gzy.rpsm_property.mapper.RoomMapper;
import edu.gzy.rpsm_property.pojo.PageResult;
import edu.gzy.rpsm_property.pojo.ResponsePojo;
import edu.gzy.rpsm_property.pojo.User;
import edu.gzy.rpsm_property.pojo.vo.UnpaidOwner;
import edu.gzy.rpsm_property.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
@Api(tags = "业主相关Api")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoomMapper roomMapper;

    @PostMapping("/insert")
    @ApiOperation(value = "新增业主信息，默认为未激活的状态，采用默认密码，生成随机账号，roomid通过级联菜单获得",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idcard", type = "String", required = true),
            @ApiImplicitParam(name = "username", type = "String", required = true),
            @ApiImplicitParam(name = "age", type = "Integer", required = true),
            @ApiImplicitParam(name = "gender", type = "Integer", required = true),
            @ApiImplicitParam(name = "user_roomid", type = "Integer", required = true),
    })
    public ResponsePojo<Integer> insertUser(@ApiIgnore User user) {
        // 验证用户名只能包含汉字
        String usernameRegex = "^[\\u4e00-\\u9fa5]+$"; // 正则表达式匹配只包含汉字
        Pattern pattern = Pattern.compile(usernameRegex);
        if (!pattern.matcher(user.getUsername()).matches()) {
            return ResponsePojo.fail(null, "用户名只能包含汉字");
        }
        // 验证 roomid 是否存在
        if (roomMapper.roomById(user.getUser_roomid().intValue()) == null) {
            return ResponsePojo.fail(null, "房间ID不存在");
        }
        // 验证年龄是否在18到100岁之间
        if (user.getAge() == null || user.getAge() < 18 || user.getAge() > 180) {
            return ResponsePojo.fail(null, "年龄必须在18到180岁之间");
        }
        // 验证性别只能为0或1
        if (user.getGender() == null || (user.getGender() != 0 && user.getGender() != 1)) {
            return ResponsePojo.fail(null, "性别只能为0（女）或1（男）");
        }
        // 验证身份证ID是否重复
        if (userService.isIdcardExist(user.getIdcard())) {
            return ResponsePojo.fail(null, "身份证ID已存在");
        }
        user.setPassword("123456");
        String name = DigestUtils.md5DigestAsHex(user.getUsername().getBytes(StandardCharsets.UTF_8)).substring(13, 20);
        name = name.concat(System.currentTimeMillis() % 1000000 + "");//生成随机账号
        user.setAccount(name);
        user.setUser_type((short) 3);
        user.setUser_status((short) 33);//未激活
        Integer result = null;
        try {
            result = userService.insertUser(user);
            return ResponsePojo.success(result);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return ResponsePojo.fail(result, "用户名重复");
        } catch (Exception e) {
            return ResponsePojo.fail(result, "新增失败,请联系管理员");
        }
    }

    @PostMapping("/pageOfOwners")
    @ApiOperation(value = "分页查询业主信息，默认为第一页，每页10条数据。", notes = "若当前页小于1，强制为1；若每页条数小于1，强制为1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", defaultValue = "1"),
            @ApiImplicitParam(name = "size", defaultValue = "10"),
    })
    public ResponsePojo<PageResult<User>> pageOfOwners(
            @ApiIgnore @RequestParam(defaultValue = "1") Integer current,
            @ApiIgnore @RequestParam(defaultValue = "10") Integer size) {
        PageResult<User> page = userService.pageOfOwner(current, size);
        return ResponsePojo.success(page);
    }

    @PutMapping("/updateStatus/{userid}")
    @ApiOperation(value = "修改用户状态，主要是更换业主后",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", type = "Integer", required = true, paramType = "path"),
            @ApiImplicitParam(name = "user_status", type = "Integer", required = true, paramType = "query",
                    allowableValues = "11,21,31,32,33")
    })
    public ResponsePojo<Integer> changeUserStatus(@ApiIgnore User user) {
        Integer status = Integer.valueOf(user.getUser_status());
        if (status == null || !(status == 11 || status == 21 || status == 31 || status == 32 || status == 33)) {
            return ResponsePojo.fail(null, "用户状态必须为11（管理员使用）、21（物业人员使用）、31（常住业主）、32（租户）或33（未激活）");
        }
        int result = userService.changeUserStatus(user);
        if (result == 0) {
            return ResponsePojo.fail(result, "该用户id失效");
        }
        return ResponsePojo.success(result);
    }

    @GetMapping("/id/{userid}")
    @ApiOperation(value = "根据用户id查询用户信息", notes = "<span style='color:red'>若查询失败，返回null</span>",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", type = "Integer", required = true)
    })
    public ResponsePojo<User> queryById(@PathVariable("userid") Integer id) {
        User u = userService.queryById(id);
        if (Optional.ofNullable(u).isPresent()) {
            return ResponsePojo.success(u);
        }
        return ResponsePojo.fail(u, "该id不存在对应用户");
    }

    @GetMapping("/unpaidOwnerList")
    @ApiOperation("单项费用的欠费名单查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", defaultValue = "1"),
            @ApiImplicitParam(name = "size", defaultValue = "10"),
            @ApiImplicitParam(name = "typeId",required = true)
    })
    public ResponsePojo<PageResult<UnpaidOwner>> unpaidOwnerList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam Integer typeId) {
        return ResponsePojo.success(userService.pageOfUnpaidOwnerList(current, size, typeId));
    }

}
